/*
 * JoinRingCommand.cpp
 *
 *  Created on: Dec 21, 2009
 *      Author: kevin
 */

#include "joinringcommand.h"
#include <sstream>
using std::ostringstream;

#include <Poco/StringTokenizer.h>
using Poco::StringTokenizer;


#include <iostream>
using std::cout;
using std::endl;

namespace Commands
{
	const string JoinRingCommand::NAME = "JoinRing";

	JoinRingCommand::JoinRingCommand(string ringname, UInt16 port, NodeData* nodedata) :
		Command( 0, true),
		_ringname(ringname),
		_port(port),
		_nodedata(nodedata)
	{
	}

	JoinRingCommand::~JoinRingCommand()
	{

	}

	void JoinRingCommand::execute()
	{
		if (_ringname == _nodedata->ringname)
		{/*
			ostringstream out;
			out << _nodedata->id;
			setResult(out.str());
			string result = out.str();

			//send result back to originator
			SocketAddress originator(_nodedata->origin.host(), _port);
			DatagramSocket sender;
			cout << "JoinRingCommand :: Going to send '" << result << "'" << endl;
			cout << "JoinRingCommand :: replied " << sender.sendTo(result.c_str(), result.size(), originator) 
				<< "B to " << originator.host().toString() << ":" << originator.port() << endl;
				*/
		} else {
			setResult("NOK");
		}
	}

	string JoinRingCommand::name()
	{
		return string(JoinRingCommand::NAME);
	}

	void JoinRingCommand::undo()
	{
		throw NotImplemented();
	}

	string JoinRingCommand::ringName()
	{
		return string(_ringname);
	}

	string JoinRingCommand::repr(){
		ostringstream out;
		// the name
		out << name() << ':';
		// The arguments, like the id of the node sending this Join command
		//out << "" << ':';
		out << ringName() << ':';
		out << _port << ':';
		// end delimiter
		out << ':';
		return out.str();

	}

	CommandCreator JoinRingCommand::creator(){
		return JoinRingCommand::makeCommand;
	}

	Command* JoinRingCommand::makeCommand(string r, void* s)
	{
		NodeData* data = (NodeData*) s;
		StringTokenizer ss(r,":");
		string name = ss[0];
		if (name.compare(JoinRingCommand::NAME) == 0)
		{
			string ringname = ss[1];
			istringstream sin(ss[2]);
			UInt16 port; sin >> port;
			return new JoinRingCommand(ringname, port, data);
		}

	}
}
